package com.gitee.jjnnzb.designpatterninspring.business.login.handler.impl;

import com.gitee.jjnnzb.designpatterninspring.business.login.entity.bo.WebLoginParam;
import com.gitee.jjnnzb.designpatterninspring.business.login.handler.LoginTemplate;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.LoginCheckManager;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.LoginRecordManager;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.TokenGenerateManager;
import com.gitee.jjnnzb.designpatterninspring.common.enums.LoginVersionEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Jjn
 * @since 2023/8/8 13:36
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WebLoginTemplateImpl extends LoginTemplate {
    
    // 导入所需要的数据库层资源接口
    private final LoginRecordManager loginRecordManager;
    private final LoginCheckManager loginCheckManager;
    private final TokenGenerateManager tokenGenerateManager;
    
    @Override
    protected void checkCaptcha(Map<String, Object> map) {
        // check captcha code...
        String captchaCode = (String) map.get("captchaCode");
        String captchaId = (String) map.get("captchaId");
        if (log.isInfoEnabled()) {
            log.info("校验图形验证码,ID:{}与数据库存储的识别结果:{}一致", captchaId, captchaCode);
        }
    }
    
    @Override
    protected void checkSystemPrivilege(Map<String, Object> map) {
        loginCheckManager.checkSystemPermission(map);
    }
    
    @Override
    protected void checkLoginIp(Map<String, Object> map) {
        // check trust ip...
        // load org trusted ip ranges...
        if (log.isInfoEnabled()) {
            log.info("校验IP是否在机构可信范围内");
        }
    }
    
    @Override
    protected void checkUser(Map<String, Object> map) {
        // check username and password
        loginCheckManager.checkUserAndPassword(map);
    }
    
    @Override
    protected void generateToken(Map<String, Object> map) {
        // generate token according to request info...
        tokenGenerateManager.generateToken(map);
    }
    
    @Override
    protected void saveLoginRecord(Map<String, Object> map) {
        loginRecordManager.saveLoginRecords(map);
    }
    
    @Override
    protected void analyseRequestInfo(Map<String, Object> map) {
        if (log.isInfoEnabled()) {
            log.info("解析请求IP,设置参数...");
        }
        WebLoginParam params = (WebLoginParam) map.get("params");
        map.put("userName", params.getUserName());
        map.put("systemCode", params.getSystemCode());
        map.put("captchaId", params.getCaptchaId());
        map.put("captchaCode", params.getCaptchaCode());
    }
    
    @Override
    protected String getVersion() {
        return LoginVersionEnum.WEB_V1.getVersion();
    }
}
